<template>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <!--
        这是一个搜索条件示例，不需要所有的话，删除这个form，并删除对应的type.ts中的queryParams
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="queryParams.username"
              placeholder="用户名"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        -->

        <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form>
    <el-card shadow="never">
        <el-button type="success" @click="openDialog()">新增</el-button>
        <el-button type="danger" :disabled="selectIds.length === 0" @click="handleDelete()">删除</el-button
        >
    </el-card>
    <el-table
            :data="tableData"
            v-loading="loading"
            max-height="80vh"
            border
            style="width: 100%"
            table-layout="auto"
            :show-overflow-tooltip="true"
            @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />


        <!-- 表格前后都是通用的，这里要定义自己的列信息  -->
        <el-table-column label="登录账号" prop="username"/>
        <el-table-column label="真实姓名" prop="realname"/>
        <el-table-column label="头像" prop="avatar"/>
        <el-table-column label="邮件" prop="email"/>
        <el-table-column label="电话" prop="phone"/>
        <el-table-column label="所属组织ID" prop="deptId"/>
        <el-table-column label="账号状态" prop="status"  :formatter="statusFormatter"/>
        <el-table-column label="职务" prop="duties"/>
        <el-table-column label="创建人" prop="createBy"/>
        <el-table-column label="创建时间" prop="createTime"/>
        <el-table-column label="更新人" prop="updateBy"/>
        <el-table-column label="更新时间" prop="updateTime"/>

        <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
                <el-button size="small" @click="openDialog(scope.row.id)"
                >修改</el-button
                >
                <el-button
                        size="small"
                        type="danger"
                        @click="handleDelete(scope.row.id)"
                >删除</el-button
                >
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="<上一页"
            next-text="下一页>"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
    />


    <!-- 表单弹窗 -->
    <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            width="500px"
            @close="closeDialog"
    >
        <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-width="100px"
        >
        <el-form-item label="登录账号" prop="username">
            <el-input v-model="formData.username" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
            <el-input v-model="formData.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
            <el-input v-model="formData.avatar" placeholder="请输入头像" />
        </el-form-item>
        <el-form-item label="邮件" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮件" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="所属组织ID" prop="deptId">
            <el-input v-model="formData.deptId" placeholder="请输入所属组织ID" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIdList">
          <el-select
              v-model="formData.roleIdList"
              multiple
              placeholder="选择角色"
              style="width: 240px"
          >
            <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select
              v-model="formData.status"
              class="m-2"
              placeholder="Select"
              size="large"
              style="width: 240px"
          >
            <el-option label="正常" :value="0"/>
            <el-option label="冻结" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="职务" prop="duties">
            <el-input v-model="formData.duties" placeholder="请输入职务" />
        </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleSubmit">确 定</el-button>
                <el-button @click="closeDialog">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
    import {reactive, ref, onMounted} from 'vue'
    import {FormInstance} from "element-plus";
    import {QueryParams} from "@/api/system/sysUser/sysUserType";
    import {SysUser,SysUserForm} from "@/api/system/sysUser/sysUserType";
    import {list,save,removeById,removeByIds,updateById,queryById} from "@/api/system/sysUser/sysUserApi";
    import {querySysRoleSelectList} from "@/api/system/sysRole/sysRoleApi";
    import {  ElMessage } from "element-plus";

    const roleOptions = ref<[]>([]);
    // 表格数据
    const tableData = ref<SysUser[]>();
    // 分页信息
    const currentPage = ref(1)
    const pageSize = ref(10)
    const small = ref(false)
    const background = ref(false)
    const disabled = ref(false)
    const total = ref(0)
    const loading = ref(false);
    // 多选的数据ID
    const selectIds = ref<string>('')
    // 新增/修改弹窗
    const dialog = reactive({
        title: "",
        visible: false,
    });
    // 表单数据
    const formData = reactive<SysUserForm>({
        id:"",
        username:"",
        realname:"",
        password:"",
        avatar:"",
        email:"",
        phone:"",
        deptId:"",
        status:0,
        delFlag:0,
        duties:"",
        roleIdList: [],
    });
    const emptyFormData = reactive<SysUserForm>({
        id:"",
        username:"",
        realname:"",
        password:"",
        avatar:"",
        email:"",
        phone:"",
        deptId:"",
        status:0,
        delFlag:0,
        duties:"",
        roleIdList: [],
    });
    // 校验用户角色
    const roleIdListValidator = (rule: any, value: any, callback: any) => {
      if(formData.roleIdList?.length===0){
        callback(new Error("请选择角色"))
      }
      callback()
    }
    // 表单校验规则
    const rules = reactive({
        username: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
        realname: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        roleIdList: [{ validator: roleIdListValidator, trigger: "blur" }]
    });

    const statusFormatter=(row, column, cellValue)=>{
      return cellValue === 0?'正常':'冻结'
    }
    // 页面加载
    onMounted(() => {
      handleQuery();
      querySysRoleSelectListFunc();
    });
    // 修改每页数据条数
    const handleSizeChange = (val: number) => {
        pageSize.value = val
        queryParams.currentPage= 1
        queryParams.pageSize = val
        handleQuery()
    }

    // 查询参数
    const queryFormRef = ref<FormInstance | null>(null);
    const queryParams = reactive<QueryParams>({
        currentPage: 1,
        pageSize: 10
    })

    //删除事件
    const handleDelete = (id?: any) => {
        if(id){
            removeById(id).then(res=>{
                ElMessage.success("删除成功");
                resetQuery()
            }).finally(() => (loading.value = false));
            return;
        }
        const ids = [selectIds.value].join(",")
        if(!ids){
            ElMessage.error("请选择数据")
            return
        }
        loading.value = true
        removeByIds(ids).then(res=>{
            ElMessage.success("删除成功");
            resetQuery()
        }).finally(() => (loading.value = false));
    }
    // 处理多选
    const handleSelectionChange = (val: any) => {
        selectIds.value = val.map((item:any)=>item.id)
    }

    // 查询角色下拉框信息
    function querySysRoleSelectListFunc(){
      querySysRoleSelectList().then(res=>{
        roleOptions.value = res.result
      })
    }
    // 处理查询
    function handleQuery() {
        list(queryParams).then(res=>{
            tableData.value = res.result.records
            total.value = res.result.total
        })
    }
    // 重置查询表单参数
    function resetQuery() {
        queryFormRef.value.resetFields();
        handleQuery();
    }

    // 页码改变
    const handleCurrentChange = (val: number) => {
        queryParams.currentPage = val
        handleQuery()
    }
    // 表单引用
    const formRef = ref<FormInstance | null>(null);
    // 打开表单弹窗
    function openDialog(id?: any) {
        dialog.visible = true;
        if (id) {
            dialog.title = "修改用户";
            queryById(id).then(res=>{
                Object.assign(formData, res.result);
            });
        } else {
            dialog.title = "新增用户";
        }
    }
    // 关闭弹窗
    const closeDialog = ()=>{
        dialog.visible = false;
        resetForm();
    }
    // 重置表单
    const resetForm = ()=>{
        formRef.value.resetFields();
        formRef.value.clearValidate();
        Object.assign(formData, emptyFormData)
    }
    // 提交表单
    const handleSubmit = ()=>{
        formRef.value.validate((valid: any) => {
            if (valid) {
                loading.value = true;
                if (formData.id) {
                    updateById(formData).then(() => {
                        ElMessage.success("修改成功");
                        closeDialog();
                        resetQuery();
                    }).finally(() => (loading.value = false));
                } else {
                    save(formData).then(() => {
                        ElMessage.success("新增成功");
                        closeDialog();
                        resetQuery();
                    }).finally(() => (loading.value = false));
                }
            }
        });
    }
</script>
